import React,{Component} from 'react';
import CommentList from './commentList';
import './commentInput.less'
class CommentInput extends Component{
  constructor(props){
      super(props);
      this.state = {
        name:"",
        content:"",
      }
  }
  nameChange(event){
    this.setState({
      name:event.target.value
    });
  }
  _setCommentName(commentName){
        localStorage.setItem("commentName",commentName);
  }
  _getCommentName(commentName){
    return localStorage.getItem("commentName")==null ?"":localStorage.getItem("commentName");
  }
  _setCommentList(comment){
      let commentList = localStorage.getItem("commentList");
      if(commentList==null){
        commentList = [];
      }else {
        commentList = JSON.parse(commentList);
      }
      commentList.push(comment);
      localStorage.setItem("commentList",JSON.stringify(commentList));
  }
  contentChange(event){
    this.setState({
      content:event.target.value
    });
  }
  handleSubmit(){
    if(this.props.onSubmit){
      if(this.state.name==""){
          alert("请输入姓名");
          return;
      }else if(this.state.content==""){
          alert("请输入评论内容");
            return;
      }
      this._setCommentName(this.state.name);

        const comment={
          name:this.state.name,
          content:this.state.content,
          createdTime:new Date().getTime(),
        }
          this._setCommentList(comment);
          this.props.onSubmit(comment)
    }
    this.setState({
      content:""
    });
  }
  componentDidMount(){
    this.textarea.focus();
  }
  componentWillMount(){
    this.setState({
      name:this._getCommentName('commentName')
    });
  }
  render(){
    return(
      <div className="comment-input">
        <div className="comment-field">
            <div className="comment-field-name">用户名：</div>
            <div className="comment-field-input"><input type="text" name="username" onChange={this.nameChange.bind(this)} value={this.state.name}/></div>
        </div>
        <div className="comment-field">
            <div  className="comment-field-name">评论内容：</div>
            <div className="comment-field-input">
              <textarea ref={(textarea)=>this.textarea = textarea} value={this.state.content} onChange={this.contentChange.bind(this)}></textarea>
            </div>
        </div>
        <div className="comment-field-btn">
          <button onClick={this.handleSubmit.bind(this)}>发表</button>
        </div>
      </div>
    )
  }
}
export default CommentInput
